package com.linxs.topcham.intefaces.controller.org;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.linxs.topcham.application.org.AgencyOrgService;
import com.linxs.topcham.application.user.UserService;
import com.linxs.topcham.domain.org.AgencyOrg;
import com.linxs.topcham.domain.user.User;
import com.linxs.topcham.intefaces.utils.MD5Utils;

@Controller
@RequestMapping(value = "/admin") 
public class ResetPasswordController {

	@Autowired
	private AgencyOrgService orgService;
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "/resetpassword", method = RequestMethod.GET) 
	public String resetpassword(Model model) {
		
		return "/org/resetpassword";
	}
	
	@RequestMapping(value = "/resetpassword", method = RequestMethod.POST) 
	@ResponseBody
	public String resetpassword(@RequestParam("password")String password, HttpServletRequest request) {
		
		User user = (User) request.getSession().getAttribute("user");
		if("admin".equals(user.getUsername())) {
			user.setPassword(new MD5Utils().generateMD5(password));
			userService.update(user); 
			return "success";
		}
		
		AgencyOrg org = orgService.get(user.getId());
		org.setPassword(new MD5Utils().generateMD5(password));
		orgService.resetAgencyOrgPassword(org);
		return "success";
	}
	
}
